<template>
  <div class="clue-form-container">
    <div class="page-header">
      <div class="left">
        <h2>{{ isEdit ? '编辑线索' : '新增线索' }}</h2>
      </div>
      <div class="right">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <el-card v-loading="loading" class="form-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="clue-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="线索姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入线索姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="form.company" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" placeholder="请输入职位" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱地址" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线索来源" prop="source">
              <el-select v-model="form.source" placeholder="请选择线索来源" style="width: 100%">
                <el-option label="官网" value="WEBSITE" />
                <el-option label="电话" value="PHONE" />
                <el-option label="邮件" value="EMAIL" />
                <el-option label="展会" value="EXHIBITION" />
                <el-option label="推荐" value="REFERRAL" />
                <el-option label="广告" value="ADVERTISEMENT" />
                <el-option label="其他" value="OTHER" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%">
                <el-option label="高" value="HIGH" />
                <el-option label="中" value="MEDIUM" />
                <el-option label="低" value="LOW" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次跟进时间" prop="nextFollowUpTime">
              <el-date-picker
                v-model="form.nextFollowUpTime"
                type="datetime"
                placeholder="请选择下次跟进时间"
                format="YYYY-MM-DD HH:mm"
                value-format="x"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

                <el-row>
          <el-col :span="24">
            <el-form-item label="行为描述" prop="behavior">
              <el-input
                v-model="form.behavior"
                type="textarea"
                :rows="3"
                placeholder="请输入线索行为或兴趣描述"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="handleSubmit" :loading="submitting">
                {{ isEdit ? '更新' : '创建' }}
              </el-button>
              <el-button @click="goBack">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { createClue, updateClue, getClue } from '@/api/clue'
import type { Clue } from '@/types/clue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const isEdit = ref(false)
const loading = ref(false)
const submitting = ref(false)

const form = reactive<Clue>({
  name: '',
  company: '',
  position: '',
  phone: '',
  email: '',
  source: '',
  priority: '',
  behavior: '',
  remark: '',
  nextFollowUpTime: ''
})

const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入线索姓名', trigger: 'blur' }],
  company: [{ required: false, message: '请输入公司名称', trigger: 'blur' }],
  phone: [
    { required: false, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: false, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  source: [{ required: true, message: '请选择线索来源', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
})

const loadClueData = async (id: number) => {
  loading.value = true
  try {
    const res = await getClue(id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('加载线索数据失败:', error)
    ElMessage.error('加载线索数据失败')
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (isEdit.value) {
          await updateClue(Number(route.params.id), form)
          ElMessage.success('更新成功')
          await recordOperation('UPDATE_CLUE', `更新线索：${form.name}`)
        } else {
          await createClue(form)
          ElMessage.success('创建成功')
          await recordOperation('CREATE_CLUE', `创建线索：${form.name}`)
        }
        goBack()
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 记录操作日志
const recordOperation = async (action: string, description: string) => {
  try {
    await axios.post('/api/logs', {
      action,
      description,
    })
  } catch (error) {
    console.error('记录操作日志失败:', error)
  }
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: isEdit.value ? '访问编辑线索页面' : '访问新增线索页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

const goBack = () => {
  router.push('/clues')
}

onMounted(() => {
  const id = route.params.id
  if (id) {
    isEdit.value = true
    loadClueData(Number(id))
  }
  recordPageAccess()
})
</script>

<style scoped>
.clue-form-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 20px;
  height: 56px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.page-header .left h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #1f2f3d;
}

.form-card {
  background-color: #fff;
}

.clue-form {
  padding: 20px;
}

.clue-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.clue-form :deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

.clue-form :deep(.el-input__inner) {
  border-radius: 4px;
}

.clue-form :deep(.el-textarea__inner) {
  border-radius: 4px;
}

.clue-form :deep(.el-select) {
  width: 100%;
}
</style>
